import router from './router'
import { useAppStoreWithOut } from '@/store/modules/app'
import { UserType } from '@/api/login/types'
import { useRouter } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { NO_REDIRECT_WHITE_LIST } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
import { signinRedirect } from '@/utils/oidc/index.js'
import config from '@/config/index'

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()

// router.beforeEach(async (to, from, next) => {
//   start()
//   loadStart()
//   const permissionStore = usePermissionStoreWithOut()
//   const userStore = useUserStoreWithOut()
//   console.log('userStore.getUserInfo', userStore.getUserInfo)

//   // 模拟
//   const appStore = useAppStoreWithOut()
//   console.log('router.beforeEach',to, from, next)
//   if (userStore.getUserInfo) {
//     console.log('是否已添加路由',permissionStore.getIsAddRouters)
//     if (permissionStore.getIsAddRouters) {
//       next()
//       // useRouter().replace({ path: to })
//       return
//     }
//     try {
//       // const { roleId } = userStore.getUserInfo as UserType
//       // await permissionStore.oidcGenerateRoutes(roleId)
//       // // console.log('permissionStore.getAddRouters', permissionStore.getAddRouters)
//       // permissionStore.getAddRouters.forEach((route) => {
//       //   router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
//       // })

//       // permissionStore.getAddRouters.forEach((route) => {
//       //   router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
//       // })
//       // const redirectPath = from.query.redirect || to.path
//       // const redirect = decodeURIComponent(redirectPath as string)
//       // const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
//       // permissionStore.setIsAddRouters(true)
//       // next(nextData)

//       // 模拟
//       // 开发者可根据实际情况进行修改
//       const roleRouters = userStore.getRoleRouters || []

//       // 是否使用动态路由
//       if (appStore.getDynamicRouter) {
//         appStore.serverDynamicRouter
//           ? await permissionStore.generateRoutes('server', roleRouters as AppCustomRouteRecordRaw[])
//           : await permissionStore.generateRoutes('frontEnd', roleRouters as string[])
//       } else {
//         await permissionStore.generateRoutes('static')
//       }

//       permissionStore.getAddRouters.forEach((route) => {
//         router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
//       })
//       const redirectPath = from.query.redirect || to.path
//       const redirect = decodeURIComponent(redirectPath as string)
//       const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
//       permissionStore.setIsAddRouters(true)
//       next(nextData)
//     } catch (error) {
//       // 退出登录
//       userStore.logout()
//     }
//   } else {
//     if (config.whiteList.indexOf(to.path) !== -1) {
//       next()
//     } else {
//       next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
//       // signinRedirect()
//     }
//   }
// })
router.beforeEach(async (to, from, next) => {
  start()
  loadStart()

  const permissionStore = usePermissionStoreWithOut()
  const appStore = useAppStoreWithOut()
  const user = useUserStoreWithOut()

  // 不检查 userStore.getUserInfo 直接处理路由
  if (permissionStore.getIsAddRouters) {
    next()
    return
  }
  console.log('from.query',  to, from)
  // 获取当前路由的完整地址
  const  tokenKey = GetQueryString('tokenKey')   
  const  token = GetQueryString('token')   
  // console.log('tokenKey', tokenKey)
  // console.log('token', token)
  // 判断tokenKey和token是否为空 来自第三方跳转登录
  if(tokenKey && token){
    const source = GetQueryString('source')   
    user.setTokenKey(tokenKey)
    user.setToken(token)
    user.setLoginSource(source)
  }
  try {
    // 如果使用动态路由，就依据不同策略生成路由
    const roleRouters = [] // 假设角色路由为空或默认值

    if (appStore.getDynamicRouter) {
      appStore.serverDynamicRouter
        ? await permissionStore.generateRoutes('server', roleRouters)
        : await permissionStore.generateRoutes('frontEnd', roleRouters)
    } else {
      await permissionStore.generateRoutes('static')
    }

    permissionStore.getAddRouters.forEach((route) => {
      router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
    })

    const redirectPath = from.query.redirect || to.path
    const redirect = decodeURIComponent(redirectPath as string)
    // 请求上有token 直接去页面
    const nextData = to.path === redirect ? to.query?.token? { path: to.path, replace: true }:{ ...to, replace: true } : { path: redirect }

    permissionStore.setIsAddRouters(true)
    next(nextData)
  } catch (error) {
    console.error('Error generating routes:', error)
    next(`/error`) // 或者重定向到错误页面
  }

})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})


function GetQueryString(name)
{
     const reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     const r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}
